package org.example;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Condition的优势：
 * 指定线程唤醒
 */
public class ProducerConsumer03 {
    public static void main(String[] args) {
        Resource3 resource = new Resource3();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    resource.printA();
                } catch (InterruptedException e) {  //  如果当前线程不是此对象的监视器的所有者(如：线程没有锁住对象)。
                    e.printStackTrace();
                }
            }
        }, "1").start();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    resource.printB();
                } catch (InterruptedException e) {  //  如果当前线程不是此对象的监视器的所有者(如：线程没有锁住对象)。
                    e.printStackTrace();
                }
            }
        }, "2").start();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    resource.printC();
                } catch (InterruptedException e) {  //  如果当前线程不是此对象的监视器的所有者(如：线程没有锁住对象)。
                    e.printStackTrace();
                }
            }
        }, "3").start();

    }
}

class Resource3 {
    private int product = 1;
    private final Lock lock = new ReentrantLock();
    private final Condition condition1 = lock.newCondition();
    private final Condition condition2 = lock.newCondition();
    private final Condition condition3 = lock.newCondition();

    public void printA() throws InterruptedException {
        try{
            lock.lock();
            while (product != 1) {
                // 等待
                condition1.await();
            }
            product = 2;
            System.out.println(Thread.currentThread().getName()+"=> AAAAAAA");
            // 指定唤醒线程 2
            condition2.signal();
        } finally {
            lock.unlock();
        }
    }

    public void printB() throws InterruptedException {
        try{
            lock.lock();
            while (product != 2) {
                // 等待
                condition2.await();
            }
            product = 3;
            System.out.println(Thread.currentThread().getName()+"=> BBBBBBB");
            // 指定唤醒线程 3
            condition3.signal();
        } finally {
            lock.unlock();
        }
    }

    public void printC() throws InterruptedException {
        try{
            lock.lock();
            while (product != 3) {
                // 等待
                condition3.await();
            }
            product = 1;
            System.out.println(Thread.currentThread().getName()+"=> CCCCCCCC");
            // 指定唤醒线程 1
            condition1.signal();
        } finally {
            lock.unlock();
        }
    }

}